#
# tcifar10_01.py
#
############################################################
#
import time
import torch
import torchvision
from torch.utils.data import DataLoader

from models import (Net)
from utils import get_dataset
import utils as c10

CIFAR10_ROOT = f"e:\sfxData\DeepLearning\cifar-10"


# 定义超参数
LR = 0.01
EPOCHS = 30
BATCH_SIZE = 64
DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

# cifar10 分类索引
classes = ('plane', 'car', 'bird', 'cat', 'deer',
           'dog', 'frog', 'horse', 'ship', 'truck')

#
# 3. 据集的准备及加载
#
train_data = c10.get_dataset(
    CIFAR10_ROOT, train=True, transform=torchvision.transforms.ToTensor())

test_data = c10.get_dataset(
    CIFAR10_ROOT, train=False, transform=torchvision.transforms.ToTensor())

# train_data = torchvision.datasets.CIFAR10(CIFAR10_ROOT, train=True, transform=torchvision.transforms.ToTensor(),
#                                           download=True)

# test_data = torchvision.datasets.CIFAR10(CIFAR10_ROOT, train=False, transform=torchvision.transforms.ToTensor(),
#                                          download=True)

print(train_data.data.shape)        # (I, H, W, C) = (50000, 32, 32, 3)
print(len(train_data.targets))     #

train_data_size = len(train_data)
test_data_size = len(test_data)


# test_data.targets
# print("训练数据集的长度为{}".format(train_data_size))
# print("测试数据集的长度为{}".format(test_data_size))
# 利用DataLoader来加载数据集
train_dataloader = DataLoader(train_data, batch_size=BATCH_SIZE, shuffle=True)
test_dataloader = DataLoader(test_data, batch_size=BATCH_SIZE, shuffle=True)

#
# 4. 神经网络、损失函数、优化器等加载
#
net = Net()
net = net.to(DEVICE)

# 损失函数
loss_fn = torch.nn.CrossEntropyLoss()
loss_fn = loss_fn.to(DEVICE)

# 优化器
optimizer = torch.optim.SGD(net.parameters(), lr=LR)

# 设置训练网络的一些参数
# 记录训练的次数
total_train_step = 0
# 记录测试的次数
total_test_step = 0

# 添加Tensorboard
# writer = SummaryWriter("logs_train")


#
# 五、训练、测试、模型保存
#
start_time = time.time()
for i in range(2):
    print("-----第{}轮训练开始------".format(i+1))

    # 训练步骤开始
    net.train()
    for data in train_dataloader:
        imgs, targets = data
        imgs = torch.Tensor(imgs).to(DEVICE)
        targets = torch.Tensor(targets).to(DEVICE)
        output = net(imgs)
        loss = loss_fn(output, targets)

        # 优化器优化模型
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        total_train_step += 1
        if total_train_step % 100 == 0:
            end_time = time.time()
            print(end_time - start_time)
            print("训练次数{}, Loss:{}".format(total_train_step, loss.item()))
            # writer.add_scalar("train_loss", loss.item(), total_train_step)

    # 评估步骤开始
    net.eval()
    total_test_loss = 0
    total_accuracy = 0
    with torch.no_grad():
        for data in test_dataloader:
            imgs, targets = data
            imgs = imgs.to(DEVICE)
            targets = targets.to(DEVICE)
            outputs = net(imgs)
            loss = loss_fn(outputs, targets)
            total_test_loss += loss.item()
            accuracy = (outputs.argmax(1) == targets).sum()
            total_accuracy += accuracy

    print("整体测试集上的Loss: {}".format(total_test_loss))
    print("整体测试集上的正确率: {}".format(total_accuracy/test_data_size))
    # writer.add_scalar("test_loss", total_test_loss, total_test_step)
    # writer.add_scalar("test_accuracy", total_accuracy / test_data_size, total_test_step)
    total_test_step += 1

    # torch.save(net, "test_{}.pth".format(i))
    # print("模型已保存")

# writer.close()
